# -*- coding: utf-8 -*-
"""================================================
-- Author:	    zengbiao
-- Create date: 2017-12-20
-- Description:	打开摄像头并进行人脸识别，可按p拍照
-- ================================================
"""
import random
import cv2
import pymysql
import time
import os
#数据库操作类

#插入数据库操作
def insert_mysql(filepath,facename):

    filepath=filepath.replace("\\","/")
    conn = pymysql.connect(host='192.168.0.125', port=3306, user='root', passwd='060621', db='face', charset='utf8')
    sql_insert = "insert into employee_picture(employee_name,employee_age,picture_Path,addTime) " \
          "values ('"+facename+"', 26,'"+filepath+"',sysdate())"
    # 使用cursor()方法获取操作游标
    cursor = conn.cursor()
    try:
        sum=cursor.execute(sql_insert)
        # 提交
        conn.commit()
    except Exception as e:
        # 错误回滚
        print(e)
        conn.rollback()
    finally:
        conn.close()
    return sum

def CatVideo(imagepath):
    try:
        source = "rtsp://admin:123456@10.2.1.152/Streaming/Channels/1"
        cap = cv2.VideoCapture(0)
        # 判断是否正常开启
        if cap.isOpened():
            classfier=cv2.CascadeClassifier("Train.xml")
            color=(0,255,0)
            frameNum = 1
            facename="UnKnow"
            while cap.isOpened():
                ret,frame=cap.read()#元组只含两个元素
                if not ret:
                    break
                grey=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
                #人脸检测，1.2和2分别为图片缩放比例和需要检测的有效点数CV_HAAR_SCALE_IMAGE
                faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.1, minNeighbors =3, minSize = (32, 32))
                if len(faceRects) > 0: #大于0则检测到人脸
                    image_name = '%s.jpeg' % (str(time.strftime("_%Y%m%d%H%M%S", time.localtime())))
                    filepath = imagepath + facename + image_name
                    #if frameNum % 40 == 1:
                    try:
                        cont = insert_mysql(filepath, facename)  # 执行数据库插入操作并返回影响行数
                        if cont > 0:
                            cv2.imwrite(filepath, frame)  # 只要监测到人脸就保存图片
                            print("保存图片成功",filepath)
                        else:
                            print("执行数据库或保存图片失败，请检查！")
                    except Exception as e:
                        print("错误信息：", e)
                    for faceRect in faceRects:  #单独框出每一张人脸
                        x, y, w, h = faceRect
                        cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 3)
                try:
                    cv2.imshow("Face Recognition",frame)
                except Exception as e:
                    print("异常错误",e)

                # 按p拍照  即可实现信息采集，后期将采集的文件连接数据库以后存放即可
                frameNum = frameNum + 1
                if cv2.waitKey(1) & 0xFF == ord("p"):
                    randomname = str(random.randint(1, 100))
                    cv2.imwrite(imagepath + randomname + ".jpg", frame)
                    break
            cap.release()
            cv2.destroyAllWindows()
    except Exception as e:
        print (e)

if __name__=="__main__":
    imagepath=os.path.dirname(os.getcwd())+"//picTest//"
    try:
        CatVideo(imagepath)
    except Exception as error:
        print("执行人脸识别过程中遇到问题：",error)
    finally:
        CatVideo(imagepath)




